package top.lingkang.authoritypro.config.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import top.lingkang.authoritypro.data.dto.ResponseResult;
import top.lingkang.authoritypro.data.pojo.UserDetails;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lingkang
 * Created by 2021/12/14
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //登录后，返回原访问页面
        RequestCache cache = new HttpSessionRequestCache();
        SavedRequest savedRequest = cache.getRequest(httpServletRequest, httpServletResponse);
        String url = "/";
        try {
            url = savedRequest.getRedirectUrl();
        } catch (Exception e) {
        }
        //重新存储user对象到session
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        httpServletRequest.getSession().setAttribute("user", userDetails);
        //让浏览器用utf8来解析返回的数据
        httpServletResponse.setHeader("Content-type", "application/json; charset=utf-8");
        httpServletResponse.setCharacterEncoding("UTF-8");//防止中文乱码
        httpServletResponse.getWriter().write(
                JSON.toJSONString(new ResponseResult<>().success("登录成功！", url))
        );
    }
}
